package com.cdn.log.interceptor;

import com.cdn.log.consts.CLogConst;
import com.cdn.log.utils.IdUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


/**
 * @author 蔡定努
 *  2023/10/06 17:33
 */
public class ClogInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String traceId = request.getHeader(CLogConst.TRACE_ID);
        MDC.put(CLogConst.TRACE_ID, StringUtils.isEmpty(traceId) ? IdUtil.simpleId() : traceId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        MDC.remove(CLogConst.TRACE_ID);
    }
}
